package com.dmai.capacity.platform.user.controller;

import java.util.*;
import java.util.stream.Collectors;

import com.dmai.capacity.platform.common.dto.PageResult;
import com.dmai.capacity.platform.common.dto.ResponseEntity;
import com.dmai.capacity.platform.common.model.LoginAppUser;
import com.dmai.capacity.platform.common.model.SysRole;
import com.dmai.capacity.platform.oauth.common.util.AuthUtils;
import com.dmai.capacity.platform.user.model.SysMenu;
import com.dmai.capacity.platform.user.service.ISysMenuService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 菜单表
 *
 * @author
 * @email
 * @date 2024-05-22 13:36:20
 */
@RestController
public class SysMenuController {

    @Autowired
    private ISysMenuService menuService;

    /**
     * 列表
     */
    @GetMapping("/menus")
//    @PreAuthorize("hasAnyAuthority('sys_menu:sysmenu:list')")
    public PageResult list(@RequestParam Map<String, Object> params) {
        PageResult pageResult = menuService.pageAll(params);
        return pageResult;
    }

    /**
     * 查询单条记录
     */
    @GetMapping("/menus/{id}")
//    @PreAuthorize("hasAnyAuthority('sys_menu:sysmenu:list')")
    public ResponseEntity findById(@PathVariable(value = "id") String id) {
        return ResponseEntity.succeed(menuService.findById(id));
    }


    /**
     * 保存
     */
    @PostMapping("/menus")
//    @PreAuthorize("hasAnyAuthority('sys_menu:sysmenu:save')")
    public ResponseEntity save(@RequestBody @Valid SysMenu menu) {
        menuService.save(menu);
        return ResponseEntity.succeed("操作成功");
    }

    /**
     * 更新
     */
    @PutMapping("/menus")
//    @PreAuthorize("hasAnyAuthority('sys_menu:sysmenu:save')")
    public ResponseEntity update(@RequestBody @Valid SysMenu menu) {
        menuService.update(menu);
        return ResponseEntity.succeed("操作成功");
    }


    /**
     * 删除
     */
    @DeleteMapping("/menus/{id}")
//    @PreAuthorize("hasAnyAuthority('sys_menu:sysmenu:delete')")
    public ResponseEntity delete(@PathVariable String id) {
        menuService.delete(id);
        return ResponseEntity.succeed("操作成功");
    }

    /**
     * 当前登录用户的菜单
     *
     * @return
     */
    @GetMapping("/menus/current")
    public ResponseEntity findMyMenu() {
        LoginAppUser loginAppUser = AuthUtils.getLoginAppUser();
        Set<SysRole> roles = loginAppUser.getRoles();
        List<SysMenu> menus = new ArrayList<>();
        Map<String, Object> params = new HashMap<>();
        if (loginAppUser.getId().equals("1")) {
            menus = menuService.findAll(params);
        } else if (!CollectionUtils.isEmpty(roles)) {
            menus = menuService.findPermission(params);
        }

        menus = menus.stream().distinct().collect(Collectors.toList());
        List<SysMenu> sysMenus = TreeBuilder(menus);
        return ResponseEntity.succeed(sysMenus);
    }


    /**
     * 两层循环实现建树
     */
    private static List<SysMenu> TreeBuilder(List<SysMenu> sysMenus) {

        List<SysMenu> menus = new ArrayList<>();
        for (SysMenu sysMenu : sysMenus) {
            if (ObjectUtils.equals("-1", sysMenu.getParentId())) {
                menus.add(sysMenu);
            }
            for (SysMenu menu : sysMenus) {
                if (menu.getParentId().equals(sysMenu.getId())) {
                    if (sysMenu.getSubMenus() == null) {
                        sysMenu.setSubMenus(new ArrayList<>());
                    }
                    sysMenu.getSubMenus().add(menu);
                }
            }
        }
        return menus;
    }
}
